/*
Copyright (C) 2009-2010 Xanadu Development Team

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2
of the License.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#include "Guild.h"
#include "GuildMembers.h"
#include "../../server/Player.h"
#include "World.h"
#include "../../tools/MySQLM.h"
string valstr(int id);

Guild::Guild(World* world, Player* player, string name) :
members(new GuildMembers),
guildname(name),
notice("Welcome to the Guild!"),
capacity(10),
points(0),
logo(0),
logoColor(0),
logoBG(0),
logoBGColor(0)
{
	ranks[0] = "Master";
	ranks[1] = "Jr. Master";
	ranks[2] = "Member";
	mysqlpp::Connection::thread_start();
	mysqlpp::Connection* conn = MySQL::getInstance()->getPool()->grab();
	mysqlpp::Query query = conn->query();
	query << "insert into guilds(worldid, leaderid, guildname, notice) values(" << valstr(world->getID()) << "," << valstr(player->getID()) << ",'" << guildname << "','" << notice << "')";
	id = (int)query.execute().insert_id();
	MySQL::getInstance()->getPool()->release(conn);
	mysqlpp::Connection::thread_end();
	members->addMember(player);
}

Guild::Guild(int guildid) :
members(new GuildMembers),
id(guildid)
{
}

Guild::~Guild() {
	mysqlpp::Connection::thread_start();
	mysqlpp::Connection* conn = MySQL::getInstance()->getPool()->grab();
	mysqlpp::Query query = conn->query();
	query << "delete from guilds where guildid=" << valstr(id);
	query.execute();
	struct RemoveGuild {
		void operator()(Player* player) {
			player->setGuild(0);
			player->setGuildRank(5);
		}
	}
	removeGuild;
	members->run(&removeGuild);
	MySQL::getInstance()->getPool()->release(conn);
	mysqlpp::Connection::thread_end();
	delete members;
}

void Guild::removeMember(int playerid) {
	members->deleteMember(playerid);
}